﻿#region MIT Licence
/*
 * Copyright (C) 2014 PdfCreative
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom 
 * the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included 
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 
 * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#endregion

using System;
using System.Collections.Generic;
using System.Text;

using PdfCreative.Pdf.Writer;

namespace PdfCreative.Pdf.Graphics
{
    /// <summary>
    /// The LinearGradientBrush class represents a brush that fills with a smooth colour gradient. The gradient is defined by two
    /// colours, and two points. The points define the range of the gradient.
    /// </summary>
    public class LinearGradientBrush : PatternBrush
    {
        // Private fields
        // ==============
        #region Private fields
        private Colour _endColour;
        private float _endX;
        private float _endY;
        private float _exponent;
        private Colour _startColour;
        private float _startX;
        private float _startY;
        #endregion



        // Object overrides
        // ================
        #region Object overrides
        /// <summary>
        /// Indicates if this LinearGradientBrush is equal to a specified other instance.
        /// </summary>
        /// <param name="obj">The other instance to compare this LinearGradientBrush with</param>
        /// <returns>A boolean indicating that the two instances are equal (true) or not</returns>
        public override bool Equals(object obj)
        {
            LinearGradientBrush other = obj as LinearGradientBrush;
            return
                null != other &&
                other._endColour == _endColour &&
                other._endX == _endX &&
                other._endY == _endY &&
                other._exponent == _exponent &&
                other._startColour == _startColour &&
                other._startX == _startX &&
                other._startY == _startY;
        }

        /// <summary>
        /// Retrieves the hash code of this linear gradient brush.
        /// </summary>
        /// <returns>The hash code</returns>
        public override int GetHashCode()
        {
            int hashCode = _endColour.GetHashCode();
            hashCode ^= _endX.GetHashCode();
            hashCode ^= _endY.GetHashCode();
            hashCode ^= _exponent.GetHashCode();
            hashCode ^= _startColour.GetHashCode();
            hashCode ^= _startX.GetHashCode();
            hashCode ^= _startY.GetHashCode();

            return hashCode;
        }
        #endregion



        // Public properties
        // =================
        #region Public properties
        /// <summary>
        /// Sets or retrieves the end colour for the gradient.
        /// </summary>
        public Colour EndColour
        {
            get { return _endColour; }
            set
            {
                if (null == value)
                    throw new ArgumentNullException("value");

                if (_startColour.ColourSpace != value.ColourSpace)
                    throw new ArgumentException("Start and end colour must use the same colour space");

                _endColour = value; 
            }
        }

        /// <summary>
        /// Sets or retrieves the X coordinate of the gradient's end point.
        /// </summary>
        public float EndX
        {
            get { return _endX; }
            set { _endX = value; }
        }

        /// <summary>
        /// Sets or retrieves the Y coordinate of the gradient's end point.
        /// </summary>
        public float EndY
        {
            get { return _endY; }
            set { _endY = value; }
        }

        /// <summary>
        /// Sets or retrieves the exponent for the gradient. The default is 1.0, and this corresponds to a strictly linear progression.
        /// </summary>
        public float Exponent
        {
            get { return _exponent; }
            set {
                if (value < 0) throw new ArgumentOutOfRangeException("value", "The exponent must be at least 0. The default is 1.0");
                _exponent = value; 
            }
        }

        /// <summary>
        /// Sets or retrieves the start colour for the brush.
        /// </summary>
        public Colour StartColour
        {
            get { return _startColour; }
            set
            {
                if (null == value)
                    throw new ArgumentNullException("value");

                if (_endColour.ColourSpace != value.ColourSpace)
                    throw new ArgumentException("Start and end colour must use the same colour space");

                _startColour = value; 
            }
        }

        /// <summary>
        /// Sets or retrieves the X coordinate of the gradient's starting point.
        /// </summary>
        public float StartX
        {
            get { return _startX; }
            set { _startX = value; }
        }

        /// <summary>
        /// Sets or retrieves the Y coordinate of the gradient's starting point.
        /// </summary>
        public float StartY
        {
            get { return _startY; }
            set { _startY = value; }
        }
        #endregion



        // Brush overrides
        // ===============
        #region Brush overrides
        /// <summary>
        /// Writes the definition for the pattern resource used by this gradient brush.
        /// </summary>
        /// <param name="graphics">The graphics object to use as a context</param>
        /// <param name="writer">The writer to write to</param>
        /// <param name="resourceReference">The resource reference</param>
        /// <param name="scope">The scope if this instance of the resource.</param>
        public override void WriteResource(
            Graphics graphics, 
            PdfWriter writer, 
            PdfResourceReference resourceReference,
            ScopedResource scope)
        {
            // We create object references for the shading parameters and the shading function.
            PdfObjectReference pattern = resourceReference.ObjectReference;
            PdfObjectReference shading = writer.CreateObjectReference();
            PdfObjectReference function = writer.CreateObjectReference();

            // We open a pattern object. The pattern type is #2, for a shading pattern.
            writer.OpenObject(pattern, "Pattern");
            writer.WriteDictionaryEntry("PatternType", "2");
            writer.WriteDictionaryEntry("Shading", shading);
            writer.CloseObject();

            // We write the shading object. This will have a type of #2, for a linear shading object, and refer
            // to a function object that interpolates the colours.

            // The start and end coordinates need to be transformed to the currently active coordinate space matrix.
            Vector start = scope.CoordinateSpace.Multiply(
                new Vector(graphics.ConvertXCoordinate(_startX), scope.TargetBounds.Height - graphics.ConvertYCoordinate(_startY), 1f));
            Vector end = scope.CoordinateSpace.Multiply(
                new Vector(graphics.ConvertXCoordinate(_endX), scope.TargetBounds.Height - graphics.ConvertYCoordinate(_endY), 1f));

            writer.OpenObject(shading, "Shading");
            writer.WriteDictionaryEntry("ShadingType", 2);
            
            writer.WriteDictionaryEntry("ColorSpace", GetPdfColourSpace(_startColour));
            writer.WriteDictionaryEntry("Coords", new float[]
                  {
                      start[0],  
                      start[1],
                      end[0], 
                      end[1]
                  }); 
            writer.WriteDictionaryEntry("Function", function);
            writer.WriteDictionaryEntry("Extend", "[true true]");
            writer.CloseObject();

            // We write the function object. This will have a type of #2, for a exponential interpolation function.
            writer.OpenObject(function);
            writer.WriteDictionaryEntry("FunctionType", "2");
            writer.WriteDictionaryEntry("Domain", "[0.0 1.0]");
            writer.WriteDictionaryEntry("C0", WriteColourArray(_startColour));
            writer.WriteDictionaryEntry("C1", WriteColourArray(_endColour));
            writer.WriteDictionaryEntry("N", _exponent);
            writer.CloseObject();
        }

        /// <summary>
        /// Retrieves the scope that this brush is valid on.
        /// </summary>
        public override ResourceScope Scope
        {
            get { return ResourceScope.CurrentCoordinateSpace; }
        }
        #endregion



        // Public constructor
        // ==================
        #region Public constructor
        /// <summary>
        /// Constructs a new linearGradientBrush instance using the specified colours and start- and end points.
        /// </summary>
        /// <param name="startColour">The start colour</param>
        /// <param name="endColour">The end colour</param>
        /// <param name="startX">The start location's X coordinate</param>
        /// <param name="startY">The start location's Y coordinate</param>
        /// <param name="endX">The end location's X coordinate</param>
        /// <param name="endY">The end location's Y coordinate</param>
        public LinearGradientBrush(Colour startColour, Colour endColour, float startX, float startY, float endX, float endY)
            : this(startColour, endColour, startX, startY, endX, endY, 1.0f) { }

        /// <summary>
        /// Constructs a new linearGradientBrush instance using the specified colours and start- and end points.
        /// </summary>
        /// <param name="startColour">The start colour</param>
        /// <param name="endColour">The end colour</param>
        /// <param name="startX">The start location's X coordinate</param>
        /// <param name="startY">The start location's Y coordinate</param>
        /// <param name="endX">The end location's X coordinate</param>
        /// <param name="endY">The end location's Y coordinate</param>
        /// <param name="exponent">The interpolation exponent (set to 1 for a linear interpolation between the start and end colours)</param>
        public LinearGradientBrush(Colour startColour, Colour endColour, float startX, float startY, float endX, float endY, float exponent)
        {
            if (null == endColour)
                throw new ArgumentNullException("endColour");

            if (null == startColour)
                throw new ArgumentNullException("startColour");

            if (startColour.ColourSpace != endColour.ColourSpace)
                throw new ArgumentException("Start and end colour must use the same colour space");

            _endColour = endColour;
            _endX = endX;
            _endY= endY;
            _exponent = exponent;
            _startColour = startColour;
            _startX = startX;
            _startY = startY;
        }
        #endregion

    } // LinearGradientBrush
}
